package xyz.lisys.servlet;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspApplicationContext;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        expressionEl(request, response);
        response.getWriter().write("Hello servlet");
    }

    public void expressionEl(HttpServletRequest request, HttpServletResponse response) {
        String elExpress = "${value1==value2}";
        Map<String, Object> contextValueMap = new HashMap<>();
        contextValueMap.put("value1", 1);
        contextValueMap.put("value2", 1);

        JspFactory jspFactory = JspFactory.getDefaultFactory();
        JspApplicationContext jspApplicationContext = jspFactory.getJspApplicationContext(getServletContext());
        PageContext pageContext = jspFactory.getPageContext(
                this, request, response,
                null, true, JspWriter.DEFAULT_BUFFER, true
        );
        ELContext elContext = pageContext.getELContext();
        ExpressionFactory expressionFactory = jspApplicationContext.getExpressionFactory();

        ValueExpression valueExp = expressionFactory.createValueExpression(elContext, elExpress, boolean.class);
        for (Map.Entry<String, Object> entry : contextValueMap.entrySet()) {
            elContext.getVariableMapper().setVariable(
                    entry.getKey(),
                    expressionFactory.createValueExpression(entry.getValue(), Integer.class)
            );
        }

        System.out.println(valueExp.getValue(elContext));
    }
}
